package com.atguigu.lease.web.app.custom.interceptor;

import com.atguigu.lease.common.exception.LeaseException;
import com.atguigu.lease.common.result.ResultCodeEnum;
import com.atguigu.lease.common.utils.JwtUtil;
import com.atguigu.lease.model.entity.UserInfo;
import com.atguigu.lease.web.app.context.LoginUserContext;
import com.atguigu.lease.web.app.service.UserInfoService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

@Component
public class AuthenticationInterceptor implements HandlerInterceptor {

    @Autowired
    private UserInfoService userInfoService;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.校验用户是否登录，若已登陆用户发送请求时会携带请求头中的token，请求头中token获取键名为access_token
        String token = request.getHeader("access_token");
        if(!StringUtils.hasLength(token)){
            //若没有则表明用户没有登录，返回用户尚未登录消息
            throw new LeaseException(ResultCodeEnum.APP_LOGIN_AUTH);
        }
        //
        Long userId = JwtUtil.parseToken(token);
        //将数据保存在线程中，后续从线程中取出数据
        LoginUserContext.setUser(userInfoService.getById(userId));
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        LoginUserContext.clear();
    }
}
